<script setup>
import { ref, onMounted, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '../../stores/user'
import axios from 'axios'
import ClockInOut from '../../components/ClockInOut.vue'

const userStore = useUserStore()
const isHR = computed(() => userStore.isHR)

const loading = ref(false)
const attendances = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('添加考勤记录')
const isEdit = ref(false)
const searchQuery = ref('')

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 排序相关
const sortField = ref('date')
const sortOrder = ref('desc')

// 筛选条件
const filters = reactive({
  keyword: '',
  userId: null,
  startDate: '',
  endDate: ''
})

const formRef = ref(null)
const form = reactive({
  id: null,
  employeeId: '',
  employeeName: '',
  date: new Date().toISOString().split('T')[0],
  checkInTime: '',
  checkOutTime: '',
  status: '正常',
  remark: ''
})

const rules = reactive({
  employeeId: [
    {
      required: true,
      message: '请选择员工',
      trigger: 'change',
      // 仅在新增时校验
      validator: (rule, value, callback) => {
        if (!isEdit.value && !value) {
          callback(new Error('请选择员工'))
        } else {
          callback()
        }
      }
    }
  ],
  date: [{ required: true, message: '请选择日期', trigger: 'change' }],
  checkInTime: [{ required: true, message: '请输入签到时间', trigger: 'blur' }],
  checkOutTime: [{ required: true, message: '请输入签退时间', trigger: 'blur' }],
  status: [{ required: true, message: '请选择考勤状态', trigger: 'change' }]
})

const employees = ref([])
const statusOptions = [
  { value: '正常', label: '正常' },
  { value: '迟到', label: '迟到' },
  { value: '早退', label: '早退' },
  { value: '缺勤', label: '缺勤' },
  { value: '请假', label: '请假' }
]

// 英文考勤状态映射
const statusEnumMap = {
  '正常': 'NORMAL',
  '迟到': 'LATE',
  '早退': 'EARLY_LEAVE',
  '缺勤': 'ABSENT',
  '请假': 'LEAVE',
  'NORMAL': 'NORMAL',
  'LATE': 'LATE',
  'EARLY_LEAVE': 'EARLY_LEAVE',
  'ABSENT': 'ABSENT',
  'LEAVE': 'LEAVE'
}

// 格式化考勤状态
const formatStatus = (status) => {
  if (!status) return '未知'
  
  const statusMap = {
    'NORMAL': '正常',
    'LATE': '迟到',
    'EARLY_LEAVE': '早退',
    'ABSENT': '缺勤',
    'LEAVE': '请假'
  }
  
  return statusMap[status] || status
}

// 根据考勤状态获取标签类型
const getStatusType = (status) => {
  const formattedStatus = typeof status === 'string' ? status : formatStatus(status)
  
  switch (formattedStatus) {
    case '正常':
      return 'success'
    case '迟到':
      return 'warning'
    case '早退':
      return 'warning'
    case '缺勤':
      return 'danger'
    case '请假':
      return 'info'
    default:
      return ''
  }
}

// 获取员工列表
const fetchEmployees = async () => {
  try {
    const response = await axios.get('/users')
    employees.value = response.data
  } catch (error) {
    console.error('获取员工列表失败:', error)
    ElMessage.error('获取员工列表失败，请重试')
  }
}

// 获取考勤记录（分页）
const fetchAttendances = async () => {
  try {
    loading.value = true
    let response;
    
    if (userStore.isHR) {
      // HR管理员可以查看所有考勤记录（分页）
      const params = {
        pageNum: currentPage.value,
        pageSize: pageSize.value,
        keyword: filters.keyword || undefined,
        userId: filters.userId || undefined,
        startDate: filters.startDate || undefined,
        endDate: filters.endDate || undefined,
        sortField: sortField.value,
        sortOrder: sortOrder.value
      }
      
      // 移除undefined的参数
      Object.keys(params).forEach(key => {
        if (params[key] === undefined) {
          delete params[key]
        }
      })
      
      response = await axios.get('/attendances/page', { params });
      
      // 处理分页数据
      attendances.value = response.data.records || [];
      total.value = response.data.total || 0;
    } else {
      // 普通员工只能查看自己的考勤记录
      response = await axios.get('/attendances/my');
      attendances.value = response.data;
      total.value = response.data.length;
    }
    
    loading.value = false;
  } catch (error) {
    console.error('获取考勤记录失败:', error);
    ElMessage.error('获取考勤记录失败，请重试');
    loading.value = false;
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchAttendances()
}

// 重置搜索
const resetSearch = () => {
  filters.keyword = ''
  filters.userId = null
  filters.startDate = ''
  filters.endDate = ''
  currentPage.value = 1
  fetchAttendances()
}

// 分页变化
const handlePageChange = (page) => {
  currentPage.value = page
  fetchAttendances()
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchAttendances()
}

// 排序变化
const handleSortChange = ({ prop, order }) => {
  if (prop && order) {
    sortField.value = prop
    sortOrder.value = order === 'ascending' ? 'asc' : 'desc'
  } else {
    // 默认排序
    sortField.value = 'date'
    sortOrder.value = 'desc'
  }
  currentPage.value = 1
  fetchAttendances()
}

// 打开添加考勤记录对话框
const openAddDialog = () => {
  isEdit.value = false
  dialogTitle.value = '添加考勤记录'
  form.id = null
  form.employeeId = ''
  form.employeeName = ''
  form.date = new Date().toISOString().split('T')[0]
  form.checkInTime = ''
  form.checkOutTime = ''
  form.status = '正常'
  form.remark = ''
  dialogVisible.value = true
}

// 打开编辑考勤记录对话框
const openEditDialog = (row) => {
  isEdit.value = true
  dialogTitle.value = '编辑考勤记录'
  form.id = row.id
  form.employeeId = row.employeeId
  form.employeeName = row.userName || row.employeeName
  form.date = row.date
  
  // 处理时间格式，提取时间部分
  if (row.checkInTime) {
    // 如果是完整的日期时间格式，只提取时间部分
    if (row.checkInTime.includes('T')) {
      const timePart = row.checkInTime.split('T')[1].substring(0, 8)
      form.checkInTime = timePart
    } else {
      form.checkInTime = row.checkInTime
    }
  } else {
    form.checkInTime = null
  }
  
  if (row.checkOutTime) {
    // 如果是完整的日期时间格式，只提取时间部分
    if (row.checkOutTime.includes('T')) {
      const timePart = row.checkOutTime.split('T')[1].substring(0, 8)
      form.checkOutTime = timePart
    } else {
      form.checkOutTime = row.checkOutTime
    }
  } else {
    form.checkOutTime = null
  }
  
  form.status = formatStatus(row.status) // 确保状态是中文格式
  form.remark = row.remark
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        
        // 预处理数据
        const payload = {
          date: form.date,
          // 修复：直接使用时间字符串，不要拼接日期
          checkInTime: form.checkInTime || null,
          checkOutTime: form.checkOutTime || null,
          status: statusEnumMap[form.status] || form.status,
          remark: form.remark || ''
        }
        
        console.log('提交的数据:', payload)
        
        if (isEdit.value) {
          await axios.put(`/attendances/${form.id}`, payload)
          ElMessage.success('考勤记录更新成功')
        } else {
          await axios.post(`/attendances?userId=${form.employeeId}`, payload)
          ElMessage.success('考勤记录添加成功')
        }
        
        // 重新获取考勤记录
        fetchAttendances()
        dialogVisible.value = false
      } catch (error) {
        console.error('提交考勤记录失败:', error)
        if (error.response && error.response.data) {
          ElMessage.error(`提交考勤记录失败: ${error.response.data.message || error.message}`)
        } else {
          ElMessage.error(`提交考勤记录失败: ${error.message}`)
        }
      } finally {
        loading.value = false
      }
    }
  })
}

// 删除考勤记录
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除此考勤记录吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      loading.value = true
      await axios.delete(`/attendances/${row.id}`)
      ElMessage.success('考勤记录删除成功')
      // 重新获取考勤记录
      fetchAttendances()
    } catch (error) {
      console.error('删除考勤记录失败:', error)
      ElMessage.error('删除失败，请重试')
    } finally {
      loading.value = false
    }
  }).catch(() => {})
}

// 员工姓名变更处理
const handleEmployeeChange = (value) => {
  const employee = employees.value.find(e => e.id === Number(value))
  if (employee) {
    form.employeeName = employee.name
  }
}

// 格式化时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  try {
    const date = new Date(dateTime)
    if (isNaN(date.getTime())) {
      return String(dateTime)
    }
    // yyyy/M/d HH:mm:ss
    const y = date.getFullYear()
    const m = date.getMonth() + 1
    const d = date.getDate()
    const hh = String(date.getHours()).padStart(2, '0')
    const mm = String(date.getMinutes()).padStart(2, '0')
    const ss = String(date.getSeconds()).padStart(2, '0')
    return `${y}/${m}/${d} ${hh}:${mm}:${ss}`
  } catch (error) {
    return String(dateTime)
  }
}

onMounted(() => {
  if (userStore.isHR) {
    fetchEmployees()
  }
  fetchAttendances()
})
</script>

<template>
  <div class="attendance-container">
    <div class="page-header">
      <div class="page-title">考勤管理</div>
      <div class="header-actions">
        <el-button 
          type="primary" 
          @click="openAddDialog"
          v-if="isHR"
        >
          <el-icon><Plus /></el-icon>添加考勤记录
        </el-button>
      </div>
    </div>
    
    <!-- 普通员工的打卡功能 -->
    <div v-if="!isHR" class="clock-in-section">
      <el-card shadow="hover" class="clock-card">
        <template #header>
          <div class="card-header">
            <h3>今日打卡</h3>
            <div class="date">{{ new Date().toLocaleDateString() }}</div>
          </div>
        </template>
        
        <div class="clock-actions">
          <ClockInOut />
        </div>
      </el-card>
    </div>
    
    <!-- 搜索和筛选区域 -->
    <div v-if="isHR" class="search-section">
      <el-card shadow="hover">
        <el-form :model="filters" inline>
          <el-form-item label="关键词">
            <el-input
              v-model="filters.keyword"
              placeholder="搜索员工姓名、备注等"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          
          <el-form-item label="员工">
            <el-select
              v-model="filters.userId"
              placeholder="选择员工"
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="employee in employees"
                :key="employee.id"
                :label="employee.name"
                :value="employee.id"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="开始日期">
            <el-date-picker
              v-model="filters.startDate"
              type="date"
              placeholder="选择开始日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 150px"
            />
          </el-form-item>
          
          <el-form-item label="结束日期">
            <el-date-picker
              v-model="filters.endDate"
              type="date"
              placeholder="选择结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 150px"
            />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>搜索
            </el-button>
            <el-button @click="resetSearch">
              <el-icon><Refresh /></el-icon>重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    
    <div class="table-container">
      <el-table 
        :data="attendances" 
        border 
        style="width: 100%" 
        v-loading="loading"
        @sort-change="handleSortChange"
        :default-sort="{ prop: 'date', order: 'descending' }"
      >
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column prop="userName" label="员工姓名" width="100">
          <template #default="{ row }">
            {{ row.userName || row.employeeName }}
          </template>
        </el-table-column>
        <el-table-column prop="departmentName" label="所属部门" width="120" />
        <el-table-column prop="date" label="日期" width="120" sortable="custom">
          <template #default="{ row }">
            {{ formatDateTime(row.date) }}
          </template>
        </el-table-column>
        <el-table-column prop="checkInTime" label="签到时间" width="120" sortable="custom">
          <template #default="{ row }">
            {{ formatDateTime(row.checkInTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="checkOutTime" label="签退时间" width="120" sortable="custom">
          <template #default="{ row }">
            {{ formatDateTime(row.checkOutTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="考勤状态" width="100" sortable="custom">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ formatStatus(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" />
        <el-table-column label="操作" width="180" fixed="right" v-if="isHR">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              size="small" 
              @click="openEditDialog(row)"
            >
              编辑
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页组件 -->
      <div v-if="isHR" class="pagination-container">
        <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </div>
    
    <!-- 添加/编辑考勤记录对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="员工" prop="employeeId">
          <template v-if="!isEdit">
            <el-select
              v-model="form.employeeId"
              placeholder="请选择员工"
              @change="handleEmployeeChange"
            >
              <el-option
                v-for="employee in employees"
                :key="employee.id"
                :label="employee.name"
                :value="employee.id"
              />
            </el-select>
          </template>
          <template v-else>
            <el-input v-model="form.employeeName" :disabled="true" />
          </template>
        </el-form-item>
        
        <el-form-item label="日期" prop="date">
          <el-date-picker
            v-model="form.date"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        
        <el-form-item label="签到时间" prop="checkInTime">
          <el-time-picker
            v-model="form.checkInTime"
            placeholder="选择签到时间"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
          />
        </el-form-item>
        
        <el-form-item label="签退时间" prop="checkOutTime">
          <el-time-picker
            v-model="form.checkOutTime"
            placeholder="选择签退时间"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
          />
        </el-form-item>
        
        <el-form-item label="考勤状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择考勤状态">
            <el-option
              v-for="option in statusOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.attendance-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 20px 15px;
  background-color: #fff;
  border-bottom: 1px solid #ebeef5;
}

.page-title {
  font-size: 20px;
  font-weight: bold;
}

.clock-in-section {
  margin: 0 20px 20px;
  padding-top: 20px;
}

.clock-card {
  margin-bottom: 0;
}

.search-section {
  margin: 0 20px 20px;
  padding-top: 20px;
}

.table-container {
  flex: 1;
  padding: 0 20px 20px;
  background-color: #fff;
  overflow-y: auto;
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px 0;
  background-color: #fff;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
}

.date {
  font-size: 14px;
  color: #909399;
}

.clock-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

/* 调整表格行高 */
:deep(.el-table__row) {
  height: 50px;
}

/* 调整表格头部样式 */
:deep(.el-table__header) {
  font-weight: bold;
  background-color: #f5f7fa;
}

/* 表格行悬停效果 */
:deep(.el-table__row:hover) {
  background-color: #f0f8ff !important;
}
</style> 